/*
 *    This file is part of CeluMap.
 *
 *    CeluMap is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    CeluMap is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Copyright 2006, 2007, 2008 Gonzalo Merayo
 *    gonzalo (at) celumap.com.ar
 *    www.celumap.com.ar
 *
 */

package form;

import lang.Lang;
import file.ResourceGetter;
import index.SoundexIndexReader;

import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;


import main.Gis;

public class StreetFinder extends Form implements CommandListener{
	
	TextField text = new TextField("", "", 40, TextField.ANY); //$NON-NLS-1$ //$NON-NLS-2$
	ChoiceGroup choice = new ChoiceGroup("", ChoiceGroup.EXCLUSIVE); //$NON-NLS-1$
	StringItem progress= new StringItem("",""); //$NON-NLS-1$ //$NON-NLS-2$
	Gis m = null;
	SoundexIndexReader index = new SoundexIndexReader(ResourceGetter.getInstance());
	public StreetFinder(Gis g) {
		super(Lang.getString("search"));
		m = g;
		append(text);
		append(progress);
		append(choice);
		setCommandListener(this);
		addCommand(new Command(Lang.getString("filter"),Command.ITEM,1));
		addCommand(new Command(Lang.getString("locate"),Command.ITEM,2));
		addCommand(new Command(Lang.getString("quit"),Command.ITEM,3));
		addCommand(new Command(Lang.getString("backToMap"),Command.ITEM,3));
		RefreshList(null);
	}
	
	public void RefreshList(String match){
		choice.deleteAll();
		if(match==null)
			return;
		progress.setText(Lang.getString("searching")); //$NON-NLS-1$
		int n = index.find(match, new ProgressListener(progress));
		for(int i=0;i<n;i++)
			choice.append(new String(index.getFigure(i).getName()), null);
	}
	
	public void commandAction(Command c, Displayable arg1) {
		if(c.getCommandType()==Command.ITEM){
			if(c.getLabel().equals(Lang.getString("filter")))
				RefreshList(text.getString());
			if(c.getLabel().equals(Lang.getString("locate"))){
				m.highlight(index.getFigure(choice.getSelectedIndex()));
			}
			if(c.getLabel().equals(Lang.getString("quit"))){
				m.quit();
			}
			if(c.getLabel().equals(Lang.getString("backToMap"))){
				m.highlight(null);
			}
		}
	}
	
}
